package com.distributer.gateway.hander;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.tomcat.util.threads.ThreadPoolExecutor;

import com.distributer.gateway.model.ServiceGroup;

/**
 * 业务处理线程池
 * @author xiaolin
 *
 */
public class BusinessThreadPool {

	private ThreadPoolExecutor threadPoolExecutor;
	
	private int minThreadCount;
	
	private int maxThreadCount;
	
	private int taskQueueLength;

	private String threadName;
	
	private ServiceGroup serviceGroup;
	
	public BusinessThreadPool( int minThreadCount, int maxThreadCount, int taskQueueLength,String threadName) {
		this.minThreadCount = minThreadCount;
		this.maxThreadCount = maxThreadCount;
		this.taskQueueLength = taskQueueLength;
		this.threadName = threadName;
		BusinessThreadFactory threadFactory = new BusinessThreadFactory(threadName);
		ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(taskQueueLength);
		this.threadPoolExecutor = new ThreadPoolExecutor(minThreadCount, maxThreadCount, 60, TimeUnit.SECONDS, workQueue, threadFactory);
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
			@Override
			public void run() {
				threadPoolExecutor.shutdown();
				try {
					if (!threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS)) {
						threadPoolExecutor.shutdownNow();
					}
				} catch (InterruptedException e) {
					threadPoolExecutor.shutdownNow();
				}
			}
		}));
	}

	public void execute(Runnable runnable){
		this.threadPoolExecutor.execute(runnable);
	}
	
	public ThreadPoolExecutor getThreadPoolExecutor() {
		return threadPoolExecutor;
	}

	public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) {
		this.threadPoolExecutor = threadPoolExecutor;
	}

	public int getMinThreadCount() {
		return minThreadCount;
	}

	public void setMinThreadCount(int minThreadCount) {
		this.minThreadCount = minThreadCount;
	}

	public int getMaxThreadCount() {
		return maxThreadCount;
	}

	public void setMaxThreadCount(int maxThreadCount) {
		this.maxThreadCount = maxThreadCount;
	}

	public int getTaskQueueLength() {
		return taskQueueLength;
	}

	public void setTaskQueueLength(int taskQueueLength) {
		this.taskQueueLength = taskQueueLength;
	}

	public String getThreadName() {
		return threadName;
	}

	public void setThreadName(String threadName) {
		this.threadName = threadName;
	}

	public ServiceGroup getServiceGroup() {
		return serviceGroup;
	}

	public void setServiceGroup(ServiceGroup serviceGroup) {
		this.serviceGroup = serviceGroup;
	}

}
